package org.credo.util;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import javax.jms.BytesMessage;
import javax.jms.Message;

/**
 * <p>Description: 各种转换方法.</p>
 * @author <a href="zhaoqianjava@qq.com">Credo</a>
 */
public class ConvertUtils {

	public static void main(String[] args) {
		//ConvertUtils.jmsBytesMessageToByteArray();
	}
	
	/**
	 * Description:IO处理--将Object对象转换为字节数组byte[].
	 * @param obj Object对象
	 * @return byte[]
	 * @throws IOException
	 */
	public static byte[] ioObjectToByteArray(Object obj) throws IOException {
		ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
		ObjectOutputStream os = new ObjectOutputStream(new BufferedOutputStream(byteStream));
		os.flush();
		os.writeObject(obj);
		os.flush();
		byte[] sendBuf = byteStream.toByteArray();
		os.close();
		return sendBuf;
	}
	
	/**
	 * Description:IO处理--将字节数组转换为Object对象
	 * @param bytes byte[],字节数组
	 * @return Object对象
	 * @throws IOException 
	 * @throws ClassNotFoundException 
	 */
	public static Object ioByteArrayToObject(byte[] bytes) throws IOException, ClassNotFoundException {
		Object obj = null;
		ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
		ObjectInputStream ois = new ObjectInputStream(bis);
		obj = ois.readObject();
		ois.close();
		bis.close();
		return obj;
	}
	
	/**
	 * Description:将JMS的BytesMessage类型的消息转换为byte[].
	 * @param msg JMS队列中消息
	 * @return 转换后的字节数组byte[]
	 * @throws Exception JMS消息不是BytesMessage类型.
	 */
	public static byte[] jmsBytesMessageToByteArray(Message msg) throws Exception {
		byte[] jmsMsg = null;
		if (msg instanceof BytesMessage) {
			//创建bytemessage对象来保存JMS信息.
			BytesMessage bytesMessage = (BytesMessage) msg;
			//创建一个直接数组,大小为BytesMessage消息体长度.
			jmsMsg = new byte[(int) bytesMessage.getBodyLength()];
			//读取bytesMessage的直接到jmsMsg.
			bytesMessage.readBytes(jmsMsg);
		} else {
			throw new Exception("数据类型错误!jms的数据不是BytesMessage类型!");
		}
		return jmsMsg;
	}
	
}
